package com.csvvip.cloud.controller;

import com.csvvip.cloud.entities.CommonResult;
import com.csvvip.cloud.entities.Payment;
import com.csvvip.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommonResult<Payment> create(@RequestBody Payment payment){
        int count = paymentService.create(payment);
        log.info("**************" + count);
        if(count > 0){
            return new CommonResult(200 , "插入数据库成功 serverPort :" + serverPort , count);
        }else{
            return new CommonResult(444 , "插入数据库失败 serverPort :" + serverPort , null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> get(@PathVariable("id") Long id){
        Payment entity = paymentService.getEntityById(id);
        log.info("**************" + entity + "当前实体信息");
        if(entity != null){
            return new CommonResult(200 , "查询成功 serverPort :" + serverPort , entity);
        }else{
            return new CommonResult(444 , "查询失败 serverPort :" + serverPort , null);
        }
    }

    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("当前服务信息：{}" , service);
        }
        List<ServiceInstance> instanceList = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instanceList) {
            log.info("当前服务名称 {} 主机：{} 端口：{} 地址：{}" , instance.getServiceId() ,instance.getHost() , instance.getPort() , instance.getUri() );
        }

        return this.discoveryClient;
    }


    @GetMapping("/payment/lb")
    public String getPaymentLB(){
        return serverPort;
    }

    @GetMapping("/payment/timeout")
    public String timeOut(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
